package com.viknix.threadpool.manager.config.util;

import com.viknix.threadpool.manager.common.util.GroupKeyUtil;
import com.viknix.threadpool.manager.server.dependence.exception.ServerProcessException;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.viknix.threadpool.manager.common.constant.Constants.*;

/**
 * @Author: Dongqi
 * @Date: 2021/10/29 15:01
 * @Version 1.0
 * @Description: Md5ConfigUtil
 */
public class Md5ConfigUtil {

    /**
     * 解析客户端数据
     *
     * @param configKeysString 客户端数据
     * @return key：threadPoolId + projectId + namespace     value：md5
     */
    public static Map<String, String> getClientMd5Map(String configKeysString) {
        Map<String, String> md5Map = new HashMap(16);
        if (StringUtils.isBlank(configKeysString)) {
            return md5Map;
        }
        int start = 0;
        List<String> tmpList = new ArrayList(3);
        for (int i = start; i < configKeysString.length(); i++) {
            char c = configKeysString.charAt(i);
            // 先按照 (char) 2 切分 tpId 、 itemId 、 md5 放到一个 tmpList 中
            if (c == WORD_SEPARATOR_CHAR) {
                tmpList.add(configKeysString.substring(start, i));
                start = i + 1;
                if (tmpList.size() > 3) {
                    throw new IllegalArgumentException(">>> invalid protocol,too much key!");
                }
                // 再按照 (char) 1 切分 nameSpace
            } else if (c == LINE_SEPARATOR_CHAR) {
                String endValue = "";
                if (start + 1 <= i) {
                    // namespace
                    endValue = configKeysString.substring(start, i);
                }
                start = i + 1;

                if (tmpList.size() == 3) {
                    // 将 threadPoolId 和 projectId 和 namespace 拼接起来
                    String groupKey = GroupKeyUtil.getKey(tmpList.get(0), tmpList.get(1), endValue);
                    // 将 md5 放到 md5Map 中
                    md5Map.put(groupKey, tmpList.get(2));
                } else {
                    throw new ServerProcessException(">>> The client data format is incorrect!");
                }
                // 清空 tmpList
                tmpList.clear();

                // Protect malformed messages
                if (md5Map.size() > 10000) {
                    throw new ServerProcessException(">>> invalid protocol, too much listener!");
                }
            }
        }
        return md5Map;
    }
}
